# coding=utf8
# 全世界最帅的帅哥
from flask_restful import Resource, reqparse
from comment.modules.account import Account
from comment.utils.decorators import login_required
from flask import g, current_app
from .serializer import AccountInfoSerializer
from comment.modules.user import User
from comment.utils.gen_trans_id import generate_trans_id
from financial.resources.transaction.const import DealType
from comment.modules.deal_record import DealRecord
from comment.modules import db


class AccountInfo(Resource):
    method_decorators = [login_required]

    def get(self):
        # 查询当前用户的资金账户
        user_id = g.user_id
        account = Account.query.filter(Account.userId == user_id).first()
        if account:
            data = AccountInfoSerializer(account).to_dict()
            return {"msg": "success!", "data": data}
        else:
            return {"message": "资金账户不存在"}, 400


class AccountExtract(Resource):
    method_decorators = [login_required]

    def post(self):
        """提现接口"""
        rp = reqparse.RequestParser()
        rp.add_argument("amount", required=True)  # 金额
        rp.add_argument("cardId", required=True)  # 卡号
        rp.add_argument("payPwd", required=True)  # 提现密码

        args = rp.parse_args()
        amount = args.amount
        card_id = args.cardId
        pay_pwd = args.payPwd

        user_id = g.user_id
        user = User.query.filter(User.id == user_id).first()

        if not user.check_pay_pwd(pay_pwd):
            return {"message": "支付密码错误", "code": 20001}
        # 查询用户资金账户
        account = Account.query.filter(Account.userId == user_id).first()

        if account:
            if account.balance < amount:
                return {"message": "超出可提取的余额"}, 400
            else:
                before_balance = account.balance
                # 提现余额减少
                account.balance = float(account.balance) - amount
                # 修改新的总金额
                account.total = float(account.total) - amount
                # 生成交易流水号
                deal_num = generate_trans_id(DealType.extract.name)
                # 提现： 调用银行的接口实现提现
                # 我这边是个人拿不到资质 模拟一下

                # 新增一条交易记录对象
                try:
                    deal_record = DealRecord(aUserId=user_id, aReceiveOrPay=1, aTransferSerialNo=deal_num,
                                             aTransferStatus=1, aBeforeTradingMoney=before_balance, amount=amount,
                                             aAfterTradingMoney=account.balance, aDescription="提现",
                                             aType=DealType.extract.value)
                    db.session.add(deal_record)
                    db.session.commit()
                    return {"msg": "提现记录成功插入到数据库"}
                except Exception as e:
                    current_app.logger.error(e)
                    db.session.rollback()
                    return {"message": "提现记录插入到数据库失败！"}, 401


class AccountRecharge(Resource):
    """资金账户的充值"""
    method_decorators = [login_required]

    def post(self):
        rp = reqparse.RequestParser()
        rp.add_argument("amount", required=True)  # 充值的金额
        rp.add_argument("selectIndex", required=True)  # 选择充值的银行卡

        args = rp.parse_args()
        amount = float(args.amount)
        bank_card_id = args.selectIndex

        user_id = g.user_id
        user = User.query.filter(User.id == user_id).first()

        # 查询用户资金账户
        account = Account.query.filter(Account.userId == user_id).first()

        if account:
            before_balance = account.balance
            # 提现余额减少
            account.balance = float(account.balance) + amount
            # 修改新的总金额
            account.total = float(account.total) + amount
            # 生成交易流水号
            deal_num = generate_trans_id(DealType.recharge.name)
            # 充值： 调用银行的接口实现充值
            # 我这边是个人拿不到资质 模拟一下

            # 新增一条交易记录对象
            try:
                deal_record = DealRecord(aUserId=user_id, aReceiveOrPay=1, aTransferSerialNo=deal_num,
                                         aTransferStatus=1, aBeforeTradingMoney=before_balance, aAmount=amount,
                                         aAfterTradingMoney=account.balance, aDescription="充值",
                                         aType=DealType.recharge.value)
                db.session.add(deal_record)
                db.session.commit()
                return {"msg": "充值记录成功插入到数据库"}
            except Exception as e:
                current_app.logger.error(e)
                db.session.rollback()
                return {"message": "充值记录插入到数据库失败！"}, 401
